<template>
  <div>
    <el-select v-model="user_id" size="mini" style="width:100%;" clearable
                @clear="clear" @change="userIdChanged" :disabled="disabled"
               filterable remote :remote-method="findUserOptions" :loading="user_loading" loading-text="加载中">
      <el-option
          v-for="item in user_list"
          :key="item.id"
          :label="item.name"
          :value="item.id">
      </el-option>
    </el-select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user_id:'',
      user_list:[],
      user_loading:false,
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    value: {
      type: String,
      default: function () {
        return null;
      }
    },
    disabled: {
      type: Boolean,
      default: function () {
        return false;
      }
    },
    extra_id: {
      type: String,
      default: function () {
        return null;
      }
    },
  },
  watch: {
    value: {
      async handler(newval, oldval) {
        if (newval != null) {
          this.user_id = newval;
          let user_name = null;
          if(this.user_id!=null) {
            this.user_list = await elm.post('/system/login/GetUserListbyID', {id: this.user_id});
          }
          for(let i=0;i<this.user_list.length;i++){
            if(this.user_list[i].id==this.user_id){user_name = this.user_list[i].name;}
          }
          this.$emit('changed',this.user_id,user_name);
        }
      },
      immediate: true
    }
  },
  created() {
    this.load();
  },
  methods: {
    async load() {
      this.loading = true;
      this.user_list = [];
      this.loading = false;
    },
    userIdChanged(){
      let user_name = null;
      for(let i=0;i<this.user_list.length;i++){
        if(this.user_list[i].id==this.user_id){user_name = this.user_list[i].name;}
      }
      this.$emit('update:value', this.user_id);
      this.$emit('change', this.user_id,user_name);
      this.$emit('changed',this.user_id,user_name);
      if(!this.em(this.extra_id)){
        this.$emit('changed_with_id',this.user_id,user_name,this.extra_id);
      }
    },
    clear() {
      this.$emit('update:value', null);
    },
    async findUserOptions(name){
      if(this.em(name)){
        this.user_list = [];
        return;
      }
      this.user_loading=true;
      this.user_list = await elm.post('/system/login/GetUserList', {'name':name });
      this.user_loading=false;
    },

    em: function (s) {
      if (s == null || s == '') { return true; }
      else { return false; }
    },
  }
}
</script>